<?php

class Job extends AppModel {

    var $actsAs = array('Auditable');
    var $name = 'Job';
    var $validate = array(
        'start_date' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'finish_date' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'address' => array(
            'notempty' => array(
                'rule' => array('notempty'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'pricetype_id' => array(
            'numeric' => array(
                'rule' => array('numeric'),
            //'message' => 'Your custom message here',
            //'allowEmpty' => false,
            //'required' => false,
            //'last' => false, // Stop validation after this rule
            //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        )
    );
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $belongsTo = array(
        'Pricetype' => array(
            'className' => 'Pricetype',
            'foreignKey' => 'pricetype_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'Pelotero' => array(
            'className' => 'Pelotero',
            'foreignKey' => 'pelotero_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    var $hasMany = array(
        'JobsDetail' => array(
            'className' => 'JobsDetail',
            'foreignKey' => 'job_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    function payAll($type, $employee_id, $date_from, $date_to, $pagar_caja) {
        //si tiene que pagar con la caja, registramos este movimiento
        if ($pagar_caja) {
            //si el dinero alcanza, vamos a registrar cada uno de estos 
            //movimientos en la caja
            $sql = 'SELECT job_id, SUM(JobsDetailsEmployee.cost) as total
                FROM jobs_details_employees as JobsDetailsEmployee, 
                     jobs_details as JobsDetail
                WHERE JobsDetail.id = JobsDetailsEmployee.jobs_detail_id
                AND paid = 0
                AND JobsDetailsEmployee.employee_id = ' . $employee_id . '
                AND JobsDetail.job_id IN (SELECT Job.id
                                                    FROM jobs as Job
                                                    WHERE Job.type = "' . $type . '"
                                                     AND Job.start_date >= "' . $date_from . '"
                                                     AND Job.finish_date <= "' . $date_to . '"
                                                     )
                GROUP BY job_id';

            $registros = $this->query($sql);
                        
            //me traigo el modelo
            App::import('Model', 'CashMovement');
            $this->CashMovement = new CashMovement();
            
            foreach ($registros as $reg) {

                $array_mov = array();
                $array_mov['user_id'] = $_SESSION['Auth']['User']['id'];
                $array_mov['type'] = 'out';
                $array_mov['movement'] = 'employee';
                $array_mov['amount'] = $reg[0]['total'];
                $array_mov['job_id'] = $reg['JobsDetail']['job_id'];
                $array_mov['employee_id'] = $employee_id;

                //guardamos el movimiento
                $this->CashMovement->create();
                $this->CashMovement->save($array_mov);
            }
        }

        //ahora marcamos como pagados estos registros
        $sql = 'UPDATE jobs_details_employees as JobsDetailsEmployee
                SET paid = 1
                WHERE JobsDetailsEmployee.employee_id = ' . $employee_id . '
                AND JobsDetailsEmployee.jobs_detail_id IN (SELECT JobsDetail.id
                                                             FROM jobs_details as JobsDetail, jobs as Job
                                                             WHERE Job.id = JobsDetail.job_id
                                                              AND Job.type = "' . $type . '"
                                                              AND Job.start_date >= "' . $date_from . '"
                                                              AND Job.finish_date <= "' . $date_to . '"
                                                              )';

        return $this->query($sql);
    }

    /**
     * Función que marca como pagado los servicios que presto un proveedor
     * y además puede registrar estos movimiento en la caja si así lo solicita
     * el parametro $pagar_caja
     * @param type $date_from
     * @param type $date_to
     * @param type $provider_id
     * @return type 
     */
    function payAllService($date_from, $date_to, $provider_id) {

        $sql = 'UPDATE jobs_details as JobsDetail
                SET provider_paid = 1
                WHERE JobsDetail.type = "service"
                AND JobsDetail.provider_id = ' . $provider_id . '
                AND JobsDetail.job_id IN (SELECT Job.id
                                             FROM jobs as Job
                                             WHERE Job.start_date >= "' . $date_from . '"
                                              AND Job.finish_date <= "' . $date_to . '"
                                                              )';

        return $this->query($sql);
    }

}
